import sys
from PyQt4.QtCore import Qt 
from PyQt4.QtGui import QLabel, QPixmap, QWidget, QFont, QTableWidget
from ..widgets.mixed_button import MixedButton
from ..data import save_manager
from . import screen_manager

class LoadFileScreen(QWidget):

	def __init__(self, *args, **kw):
		QWidget.__init__(self, *args, **kw)
		self.setGeometry(0, 0, 1024, 768)
#
#		background for the table
#
		wood = QLabel(self)
		wood.setGeometry(0, 0, 1024, 768)
		path = "resources/wood.jpg"
		wood.setPixmap(QPixmap(path))
#
#		title label
#
		title = QLabel(self)
		title.setGeometry((1024-550)/2, 50,550,40)
		title.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter )
		title.setText("Please Select A File")
#
#		font and color
#
		font = QFont("Gabrielle", 24)
		self.font = font
		title.setFont(font)
		title.setStyleSheet("color : yellow")
#
#		create the table widget and set the styling
#
#		there's rather a lot to do here...
#
		self.table = QTableWidget(self)
		self.table.setGeometry((1024-816)/2,120,816,420)
#
#		catch the signal when the selected cell changes
#
		self.table.currentCellChanged.connect(self.cell_changed)
		self.table.cellDoubleClicked.connect(self.cell_double_clicked)
#
#		set three columns and set their widths
#
		self.table.setColumnCount(3)
		self.table.setColumnWidth(0, 60)
		self.table.setColumnWidth(1, 430)
		self.table.setColumnWidth(2, 300)
#
#		set a style sheet for the table.
#		basically we're turning off the background for the table
#		and making the cells use dark leather with a yellow rounded frame
#
		ss = """
			QTableWidget {
				background-color: transparent;
			}
			QTableWidget:item {
				color: yellow;
				border-width : 2px;
				border-color : yellow;
			}
		"""
		self.table.setStyleSheet(ss)
#
#		more styling. turn off the grid and the headers
#
		self.table.setShowGrid(False)
		self.table.horizontalHeader().hide()
		self.table.verticalHeader().hide()
#
#		get the scroll bar and apply a style sheet
#		the stylesheet is huge, so I've defined it at the
#		end of the class definition
#
		sb = self.table.verticalScrollBar()
		sb.setStyleSheet(LoadFileScreen.scroll_bar_style)
#
#		OK, let's have a couple of buttons
#
		self.back_butt = MixedButton("Back", self)
		self.back_butt.setGeometry(105, 580, 210, 50)
		self.back_butt.clicked.connect(
			self.back_button_func
		)
#
#		and another one to load
#
		self.load_butt = MixedButton("Load", self)
		self.load_butt.setGeometry(715, 580, 210, 50)
		self.load_butt.clicked.connect(
			self.load_button_func
		)
#
#		set a smaller font size for the cells
#
		self.font = QFont("Gabrielle", 20)
#
#		hide the screen until its needed
#
		self.hide()

	def set_data(self, l):
#
#		empty the table so we don't get the rows from last time
#		There's an argument for adding enough rows to fill the
#		frame, even if they're empty
#
		self.table.clear()
		self.table.setRowCount(0)
#
#		item and itemAt don't seem to work if I set the cell widget
#		so let's keep our own matrix of cell contents
#
		self.cells = []
#
#		make a note of the list so we can get the
#		hidden filename 
#
		self.list = l
#
#		loop over the dictionaries in the list
#
		count = 0
		for d in l:
			temp = []
#
#			shorthand variables for the values to be displayed
#
			index = count
			name = d["name"]
			stamp = d["stamp"]
			print "adding {}, {}, {}".format(
				index, name, stamp
			)
#
#			add a row to hold the data
#
			self.table.insertRow(count)
			self.table.setRowHeight(count, 60)

#
#			item for the index column
#
			cell = self.make_cell(60, index+1)
			self.table.setCellWidget(count, 0, cell)
			temp +=[ cell ]
#
#			same for name
#
			cell = self.make_cell(300, name)
			self.table.setCellWidget(count, 1, cell)
			temp +=[ cell ]
#
#			and again for timestamp
#
			cell = self.make_cell(300, stamp)
			self.table.setCellWidget(count, 2, cell)
			temp +=[ cell ]

			self.cells.append(temp)

			count += 1

	def make_cell(self, width, data):
#
#		item for the index column
#
#		start with a label
#
		cell = QLabel(self)
#
#		set the geometry and font
#
		cell.setGeometry(0, 0, width, 50)
		cell.setFont(self.font)
#
#		convert arg to text and set as text
#
		cell.setText("{}".format(data))
#
#		center the cell
#
		cell.setAlignment(Qt.AlignVCenter | Qt.AlignHCenter )
#
#		style the widget 
#
		cell.setStyleSheet(LoadFileScreen.dark_style)
		return cell


#
#	load the game. The Save Manager does the file reading
#
	def do_load(self, row):
		loaded_ok = save_manager.load_from_index(row)
		name = save_manager.get_name_from_index(row)
		print "loaded ok = ", loaded_ok
		if not loaded_ok:
			print "load error for 'name'"
			s = "load failed for file '{}'".format(name)
			screen_manager.printer(s)
			return

		screen_manager.show("main screen")
		s = "'{}' loaded, Master.".format(name)
		screen_manager.printer(s)

#
#	I guess I'll have to run this as a giant popup
#	so the back button is going to close the window to
#	re-display wherever the user was before
#
	def back_button_func(self):
#
#		if the game instance is set, hide the
#		window to reveal the game screen
#
		if self.game:
			self.hide()
#
#		otherwise, settle for a debug message so I
#		can tell it is working
#
		else:
			print "back button"

	def load_button_func(self):
		self.do_load(self.table.currentRow())

	def cell_double_clicked(self, row, col):
		self.do_load(row)

	def cell_changed(self, cr, cc, pr, rc):
		print "cell changed: {},{},{},{}".format(
			cr, cc, pr, rc
		)
#
#		if previous row is the same as the current row
#		then nothing to do
#
		if pr == cr:
			return
#
#		set the new row to use the lighter colour leather background
#
		for col in range(0,3):
#
#			get the cell and change the style
#			there's probably a selector that will do this
#
			cell = self.cells[cr][col]
			cell.setStyleSheet(LoadFileScreen.light_style)
#
#			if the previous row is -1, this is the first time
#			so there's nothing more to do on this iteration
#
			if pr == -1:
				continue
#
#			otherwise get the cells and set the dark background
#
			cell = self.cells[pr][col]
			cell.setStyleSheet(LoadFileScreen.dark_style)


#
#	we need to refresh the save list before we display
#	the screen
#
	def show(self):
		save_manager.scan()
		self.set_data(save_manager.saves)
		QWidget.show(self)

#
#	honking big style sheet for scroll bars
#
	scroll_bar_style = """
/*
 *		this does the background of the scroll bar
 */
		QScrollBar:vertical {
			border: 1px solid black;
			background: OrangeRed;
			width: 15px;
			margin: 22px 0 22px 0;
		}
/*
 *		this is the bit in the middle that can be dragged
 */
		QScrollBar::handle:vertical {
			background: yellow;
			min-height: 20px;
			width: 25px;
		}
/*
 *		these appear to make boxes in the up and down arrow icons
 *		probably you could make them use images. This turns them off
 */
		QScrollBar::add-line:vertical {
			border: 0px solid grey;
			background: transparent;
			height: 15px;
			subcontrol-position: bottom;
			subcontrol-origin: margin;
		}
/*
 *		this is the other one of the above. It's at the top,
 *		so this would have scrolled up
 */
		QScrollBar::sub-line:vertical {
			border: 0px solid grey;
			background: transparent;
			height: 15px;
			subcontrol-position: top;
			subcontrol-origin: margin;
		}
/*
 *		replaced the whole up arrow icon with an image
 */
		QScrollBar::up-arrow:vertical {
			border: 0px solid orange;
			width: 15px;
			height: 15px;
			background-image: url(resources/sb_up.png);
		}
/*
 *		similar for down.
 */
		QScrollBar::down-arrow:vertical {
			border: 0px solid orange;
			width: 15px;
			height: 15px;
			background-image: url(resources/sb_down.png);
		}
/*
 *		don't know what this is. Sounds like it would define a button
 *		to scroll by a page at a time. I'll leave it turned off
 */
		QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical {
			background: none;
		}
	"""

#
#	style for dark cells - the non-selected ones
#
	dark_style = """
		QLabel {
			margin : 5px;
			color:yellow;
			border-style : solid;
			border-width : 3px;
			border-color : yellow;
			border-radius: 10px;
			background-image : url("resources/dark_leather.png")
		}
	"""
#
#	light leather background for current row
#
	light_style = """
		QLabel {
			margin : 5px;
			color:yellow;
			border-style : solid;
			border-width : 3px;
			border-color : yellow;
			border-radius: 10px;
			background-image : url("resources/light_leather.png")
		}
	"""



if __name__ == "__main__":

	files = [
		{ 	"name" : "The Doghouse",
			"stamp" : "2013-09-15 14:44",
			"file" : "The Doghouse.sav"
		},
		{ 	"name" : "Slut Central",
			"stamp" : "2012-07-15 10:23",
			"file" : "Slut Central.sav"
		},
		{ 	"name" : "Pussy Paradise",
			"stamp" : "2010-07-15 10:23",
			"file" : "Pussy Paradise.sav"
		},
		{ 	"name" : "Rent-A-Cunt",
			"stamp" : "2009-07-15 10:23",
			"file" : "Rent-A-Cunt.sav"
		},
		{ 	"name" : "Cheap Fucks",
			"stamp" : "2008-07-15 10:23",
			"file" : "Cheap Fucks.sav"
		},
		{ 	"name" : "Hotel Bonk",
			"stamp" : "2008-07-15 10:23",
			"file" : "Hotel Bonk.sav"
		},
		{ 	"name" : "Rumpy Pumpy!",
			"stamp" : "2008-07-15 10:23",
			"file" : "Rumpy Pumpy!.sav"
		},
		{ 	"name" : "Slap And Tickle",
			"stamp" : "2008-07-15 10:23",
			"file" : "Slap And Tickle.sav"
		},
	]

	app = QApplication(sys.argv)

	top = LoadFileScreen()
	top.move((1024-897)/2, 100)
	top.set_data(files)

	#w.setTitle("Excuse me!")
	#msg = "In order to proceed, you should first\nname your establishment."
	#w.setMessage(msg)
	#w.setButton("Very Well.")
	#w.setHandler(QtCore.QCoreApplication.instance().quit)

	top.show()
	sys.exit(app.exec_())





